package gui.view;

import java.awt.Component;

import javax.swing.JList;
import javax.swing.ListModel;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import gui.parser.Attr;
import gui.view.adapter.BaseAdapter;

public class ListView extends View {
	private JList<String> view;
	// private JScrollPane layout;
	private BaseAdapter adapter;
	private OnItemClickListener onItemClickListener;

	public ListView(Attr attr) {
		super(attr);
	}

	@Override
	protected void addAllListener() {
		super.addAllListener();
		view.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				if (!e.getValueIsAdjusting() && onItemClickListener != null) {
					onItemClickListener.onItemClick(view.getSelectedIndex(),
							adapter.getItemId(view.getSelectedIndex()));
				}
			}
		});
		view.setModel(new ListModel<String>() {

			@Override
			public void removeListDataListener(ListDataListener l) {
			}

			@Override
			public int getSize() {
				return adapter == null ? 0 : adapter.getCount();
			}

			@Override
			public String getElementAt(int index) {
				return adapter.getItem(index);
			}

			@Override
			public void addListDataListener(ListDataListener l) {
			}
		});
	}

	@Override
	public void init() {
		super.init();
		setEnable(true);
		view = new JList<>();
		// layout = new JScrollPane(view);
	}

	@Override
	public void invalidate() {
		super.invalidate();
		setBounds();
	}

	public BaseAdapter getAdapter() {
		return adapter;
	}

	@Override
	public Component getView() {
		return view;
	}

	public JList<String> getList() {
		return view;
	}

	public void setAdapter(BaseAdapter adapter) {
		this.adapter = adapter;
		adapter.addView(this);
		invalidate();
	}

	public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
		this.onItemClickListener = onItemClickListener;
	}

	public static interface OnItemClickListener {
		void onItemClick(int position, long id);
	}
}
